import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../utils/router.dart';
import 'UnauthorizedException.dart'; // 自定义异常类

class AuthProvider extends ChangeNotifier {
  String? _token;
  String? _userId;
  bool _loading = true;

  String? get token => _token;

  String? get userId => _userId;

  bool get isLoading => _loading;

  bool get isLoggedIn => _token != null;

  AuthProvider() {
    _loadTokenAndUserId();
  }

  Future<void> init() async {
    await _loadTokenAndUserId();
  }

  void handleApiError(dynamic error) {
    if (error is UnauthorizedException) {
      logout(); // 清除缓存
      if (!globalRouter.location.startsWith('/login')) {
        globalRouter.go('/login'); // ✅ 跳转登录
      }
    }
  }

  Future<void> loadToken() async {
    final prefs = await SharedPreferences.getInstance();
    _token = prefs.getString('token');
    _userId = prefs.getString('userId');
    _loading = false;
    notifyListeners();
  }

  Future<void> _loadTokenAndUserId() async {
    final prefs = await SharedPreferences.getInstance();
    _token = prefs.getString('token');
    _userId = prefs.getString('userId');
    _loading = false;
    notifyListeners();
  }

  Future<void> login(String token, String userId) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('token', token);
    await prefs.setString('userId', userId);
    _token = token;
    _userId = userId;
    notifyListeners();
  }

  Future<void> logout() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove('token');
    await prefs.remove('userId');
    _token = null;
    _userId = null;
    notifyListeners();
  }
}
